<template>
  <div class="app-container">
    <div class="filter-container">
      <el-form ref="queryForm" :inline="true" :model="queryParams" size="small">
        <el-form-item prop="params.roleName">
          <el-input
            v-model="queryParams.params.roleName"
            class="filter-item"
            clearable
            placeholder="角色名称"
            style="width: 150px;"
          />
        </el-form-item>
        <!-- 按钮 -->
        <el-button
          v-permission="['/sys/role/search']"
          v-waves
          class="filter-item"
          icon="el-icon-search"
          size="small"
          style="margin-left: 10px;"
          type="primary"
          @click="getDataList"
        >查询
        </el-button>
        <el-button
          v-permission="['/sys/role/add']"
          v-waves
          class="filter-item"
          icon="el-icon-plus"
          size="small"
          type="primary"
          @click="handleOpenDialog('add')"
        >新增
        </el-button>
        <el-button
          v-permission="['/sys/role/search']"
          v-waves
          class="filter-item"
          icon="el-icon-refresh"
          size="small"
          type="primary"
          @click="resetQueryForm"
        >重置
        </el-button>
      </el-form>
    </div>
    <div class="table-container">
      <el-table
        v-loading="dataLoading"
        :data="dataList"
        border
        element-loading-text="拼命加载中"
        fit
        highlight-current-row
        size="small"
        style="width: 100%;"
      >
        <el-table-column :index="shownIndex" align="center" fixed label="序号" type="index" />
        <el-table-column align="center" label="角色名称" prop="roleName" />
        <el-table-column align="center" label="角色标签">
          <template slot-scope="scope">
            <el-tag :key="scope.row.roleName" type="warning">{{ scope.row.roleName }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column :show-overflow-tooltip="true" align="center" label="备注" prop="remark" />
        <el-table-column align="center" label="操作" width="300">
          <template slot-scope="scope">
            <el-button
              v-permission="['/sys/role/update']"
              v-waves
              size="mini"
              type="primary"
              @click="handleOpenDialog('update', scope.row)"
            >编辑
            </el-button>
            <el-button
              v-permission="['/sys/role/permission']"
              v-waves
              size="mini"
              type="warning"
              @click="handleOpenDialog('permission', scope.row)"
            >权限
            </el-button>
            <el-button
              v-permission="['/sys/role/delete']"
              v-waves
              size="mini"
              type="danger"
              @click="handleDelete(scope.row)"
            >删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div class="pagination-container">
      <el-pagination
        :current-page="queryParams.page"
        :page-size="queryParams.size"
        :page-sizes="[10,20,30, 50]"
        :total="total"
        background
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
    <!-- 新增-编辑对话框 -->
    <el-dialog
      v-loading="dialogLoading"
      :close-on-click-modal="false"
      :title="dialogTitleMap[dialogStatus]"
      :visible.sync="dialogFormVisible"
      element-loading-text="保存中"
      width="550px"
    >
      <el-form
        ref="dataForm"
        :model="dataForm"
        :rules="rules"
        label-position="right"
        label-width="150px"
        size="small"
        style="width: 80%;"
      >
        <el-form-item label="角色名称：" prop="roleName">
          <el-input v-model="dataForm.roleName" placeholder="角色名称" />
        </el-form-item>
        <el-form-item label="备注信息：" prop="remark">
          <el-input v-model="dataForm.remark" placeholder="备注信息" type="textarea" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button size="small" @click="dialogFormVisible = false">取消</el-button>
        <el-button v-if="dialogStatus ==='add'" size="small" type="primary" @click="handleAdd">确定</el-button>
        <el-button v-else size="small" type="primary" @click="handleUpdate">确定</el-button>
      </div>
    </el-dialog>
    <!-- 权限分配对话框 -->
    <el-dialog
      v-loading="dialogLoading"
      :close-on-click-modal="false"
      :title="dialogTitleMap[dialogStatus]"
      :visible.sync="dialogPermissionVisible"
      element-loading-text="保存中"
      width="800px"
    >
      <el-tree
        ref="permissionTreeRef"
        :data="treeData"
        :default-checked-keys="hasPermissions"
        :default-expanded-keys="[1]"
        :props="defaultProps"
        class="permission-tree-container"
        highlight-current
        node-key="id"
        show-checkbox
      />
      <div slot="footer" class="dialog-footer">
        <el-button size="small" @click="dialogPermissionVisible = false">取消</el-button>
        <el-button size="small" type="primary" @click="permissionAssign">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import { add, del, fetchList, getAssignedPermission, savePermissionAssign, update } from '@/api/system/role'
import { fetchTreeData } from '@/api/system/permission'

export default {
  name: 'Role',
  data() {
    return {
      dataLoading: false,
      dialogStatus: '',
      total: 0,
      dialogLoading: false,
      dialogFormVisible: false,
      dialogPermissionVisible: false,
      currentRow: null, // 当前操作行的数据
      dialogTitleMap: {
        add: '新增',
        update: '编辑',
        permission: '权限分配'
      },
      defaultProps: {
        children: 'children',
        label: 'name'
      },
      queryParams: {
        page: 1,
        size: 20,
        params: {
          roleName: ''
        }
      },
      dataList: [],
      treeData: [], // 权限树数据
      hasPermissions: [], // 已有权限数据
      rules: {
        roleName: [{ required: true, message: '名称不能为空', trigger: 'change' }]
      },
      dataForm: {
        roleName: '',
        remark: ''
      }
    }
  },
  mounted() {
    this.init()
  },
  methods: {
    init() {
      const ininDataFunc = async() => {
        this.getDataList()
      }
      ininDataFunc()
    },
    shownIndex(index) {
      return (this.queryParams.page - 1) * this.queryParams.size + index + 1
    },
    handleSizeChange(size) {
      this.queryParams.size = size
      this.getDataList()
    },
    handleCurrentChange(page) {
      this.queryParams.page = page
      this.getDataList()
    },
    getDataList() {
      this.dataLoading = true
      fetchList(this.queryParams)
        .then(res => {
          console.log(res)
          this.dataList = res.data.records
          this.total = res.data.total
          this.dataLoading = false
        })
        .catch(err => {
          console.log(err)
          this.dataLoading = false
        })
    },
    resetQueryForm() {
      this.$refs['queryForm'].resetFields()
      this.queryParams.page = 1
      this.getDataList()
    },
    handleDelete(rowData) {
      this.$confirm('是否删除该记录？', '删除提示', { type: 'warning' })
        .then(() => {
          del(rowData.id)
            .then(res => {
              console.log(res)
              this.$message.success(res.msg || '删除成功')
              this.getDataList()
            })
            .catch(err => {
              console.log(err)
              this.$message.error(err || '删除失败')
            })
        })
        .catch(cancel => {
          console.log(cancel)
        })
    },
    handleAdd() {
      // 先进行表单校验
      this.$refs['dataForm'].validate(valid => {
        if (valid) {
          this.dialogLoading = true
          add(this.dataForm)
            .then(res => {
              console.log(res)
              this.$message.success(res.msg || '新增成功')
              this.dialogLoading = false
              this.dialogFormVisible = false
              this.resetDataForm()
              this.getDataList()
            })
            .catch(err => {
              console.log(err)
              this.dialogLoading = false
            })
        }
      })
    },
    handleUpdate() {
      // 先进行表单校验
      this.$refs['dataForm'].validate(valid => {
        if (valid) {
          this.dialogLoading = true
          update(this.dataForm)
            .then(res => {
              console.log(res)
              this.$message.success(res.msg || '修改成功')
              this.dialogLoading = false
              this.dialogFormVisible = false
              this.resetDataForm()
              this.getDataList()
            })
            .catch(err => {
              console.log(err)
              this.dialogLoading = false
            })
        }
      })
    },
    handleOpenDialog(type, rowData) {
      // 表单状态为新增/编辑、打开新增/编辑窗口
      this.resetDataForm()
      this.dialogStatus = type
      if (rowData) {
        this.currentRow = rowData
      }
      if (type === 'update') {
        this.dataForm = JSON.parse(JSON.stringify(rowData))
        this.dialogFormVisible = true
      } else if (type === 'add') {
        this.dialogFormVisible = true
      } else if (type === 'permission') {
        this.hasPermissions = []
        // 获取权限树数据
        fetchTreeData()
          .then(res => {
            console.log(res)
            this.treeData = res.data
          })
          .catch(err => {
            console.log(err)
          })
        // 获取该角色已有权限数据
        getAssignedPermission({
          size: 9999,
          params: { roleId: this.currentRow.id }
        })
          .then(res => {
            this.hasPermissions = []
            res.data.records.forEach((item, index, array) => {
              this.hasPermissions.push(item.permissionId)
            })
            this.dialogPermissionVisible = true
          })
          .catch(err => {
            console.log(err)
          })
      }
    },
    // 手动重置表单
    resetDataForm() {
      if (this.$refs['dataForm']) {
        // 由于编辑数据的时候会导致表单对象的初始化值发生变更，所以在重置表单前先手动重置表单对象的值
        this.dataForm = {
          roleName: '',
          remark: ''
        }
        this.$refs['dataForm'].resetFields()
      }
    },
    filterByRoleName(query, item) {
      return item.label.indexOf(query) > -1
    },
    permissionAssign() {
      // 获取选中的key数组
      var checked = this.$refs.permissionTreeRef.getCheckedKeys(false)
      var itemList = []
      checked.forEach((value, index, array) => {
        itemList.push({ roleId: this.currentRow.id, permissionId: value })
      })
      // 传递一个权限ID为空的对象，方便后台处理是哪个角色分配0个权限特殊情况处理
      if (itemList.length === 0) {
        itemList.push({ roleId: this.currentRow.id, permissionId: null })
      }
      savePermissionAssign(itemList)
        .then(res => {
          this.$message.success(res.msg || '分配权限成功')
          this.dialogPermissionVisible = false
        })
        .catch(err => {
          console.log(err)
        })
    }
  }
}
</script>
<style scoped>
.el-form .el-select {
  width: 100%;
}
</style>
